<template>
  <ArtTableFullScreen>
    <div id="table-full-screen">
      <el-card shadow="never" class="art-table-card">
        <ArtTableHeader
          :columnList="columnOptions"
          v-model:columns="columnChecks"
          @refresh="handleRefresh"
        >
          <template #left>
            <el-button @click="showDialog('add')" :icon="Plus" v-ripple>新增</el-button>
          </template>
        </ArtTableHeader>
        <VueDraggable target="tbody" v-model="tableData" :animation="150" @change="handDragChange">
          <art-table :data="tableData" :loading="loading" :pagination="false">
            <template #default>
              <el-table-column v-for="col in columns" :key="col.prop" v-bind="col" />
            </template>
          </art-table>
        </VueDraggable>
        <el-dialog
          v-model="dialogVisible"
          :title="dialogType === 'add' ? '新增分类' : '修改分类'"
          width="40%"
        >
          <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
            <el-form-item label="标题" prop="name">
              <el-input v-model="formData.name" placeholder="请输入分类名称" />
            </el-form-item>
            <el-form-item label="封面" prop="cover">
              <ArtImageUpload v-model:files="formData.cover"></ArtImageUpload>
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" @click="handleSubmit">提交</el-button>
            </div>
          </template>
        </el-dialog>
      </el-card>
    </div>
  </ArtTableFullScreen>
</template>

<script setup lang="ts">
  import { FormInstance } from 'element-plus'
  import { ElMessageBox, ElMessage } from 'element-plus'
  import { Plus } from '@element-plus/icons-vue'
  import type { FormRules } from 'element-plus'
  import { TypeService } from '@/api/common/type'
  import { VueDraggable } from 'vue-draggable-plus'
  import { useCheckedColumns } from '@/composables/useCheckedColumns'
  import ArtButtonTable from '@/components/core/forms/ArtButtonTable.vue'
  import ArtImagePreview from '@/components/image/ArtImagePreview.vue'
  const dialogType = ref('add')
  const dialogVisible = ref(false)

  const formData = reactive({
    name: '',
    pid: 2,
    cover: ''
  })

  const pid = 2
  const loading = ref(false)
  const tableData = ref<any>([])

  // 列配置
  const columnOptions = [
    { label: '勾选', type: 'selection' },
    { label: 'ID', prop: 'id' },
    { label: '标题', prop: 'name' },
    { label: '封面', prop: 'cover' },
    { label: '操作', prop: 'operation' }
  ]
  // 动态列配置
  const { columnChecks, columns } = useCheckedColumns(() => [
    // { type: 'selection' }, // 勾选列
    // { type: 'expand', label: '展开', width: 80 }, // 展开列
    { type: 'index', label: '序号', width: 80, align: 'center' }, // 序号列
    { prop: 'id', label: 'ID', align: 'center' },
    { prop: 'name', label: '标题' },
    {
      prop: 'cover',
      label: '封面',
      formatter: (row: any) => {
        return h(ArtImagePreview, { src: row.cover })
      }
    },
    {
      prop: 'operation',
      label: '操作',
      width: 200,
      align: 'center',
      fixed: 'right', // 固定在右侧
      // disabled: true,
      formatter: (row: any) => {
        return h('div', [
          h(ArtButtonTable, {
            type: 'edit',
            onClick: () => showDialog('edit', row)
          }),
          h(ArtButtonTable, {
            type: 'delete',
            onClick: () => deleteTableRow(row)
          })
        ])
      }
    }
  ])
  onMounted(() => {
    getTableData()
  })
  // 刷新
  const handleRefresh = () => {
    getTableData()
  }
  // 获取列表
  const getTableData = async () => {
    loading.value = true
    const { data } = await TypeService.getChildCate(pid)
    tableData.value = data
    loading.value = false
  }

  // 显示弹窗
  const showDialog = (type: string, row?: any) => {
    if (type === 'edit' && row) {
      formData.id = row.id
      formData.name = row.name
      formData.cover = row.cover
    } else {
      formData.id = undefined
      formData.name = ''
      formData.cover = ''
    }
    dialogVisible.value = true
    dialogType.value = type
  }

  const deleteTableRow = (row: any) => {
    ElMessageBox.confirm(`确定要删除${row.name}吗？`, '删除分类', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    })
      .then(() => {
        return TypeService.delChildCate(row.id)
      })
      .then(() => {
        getTableData()
        ElMessage.success('删除成功')
      })
  }

  const rules = reactive<FormRules>({
    name: [{ required: true, message: '请输入分类标题', trigger: 'blur' }]
  })

  // 表格拖拽事件
  const handDragChange = () => {
    // console.log(e, e.oldIndex, e.newIndex)
  }

  const formRef = ref<FormInstance>()

  const handleSubmit = async () => {
    if (!formRef.value) return

    await formRef.value.validate(async (valid) => {
      if (valid) {
        if (dialogType.value === 'add') {
          await TypeService.addChildCate(formData)
        } else {
          await TypeService.updateChildCate(formData)
        }
        await getTableData()
        ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
        dialogVisible.value = false
      }
    })
  }
</script>
